<style scoped lang="scss">
.main {
  padding: 2vh;
  background-color: #2d3748;
}
.n-card {
  width: 20vw;
}
.n-slider {
  margin-top: 2vh;
}
.coordinate {
  margin-top: 2vh;
}
.n-input-number {
  width: 8vw;
}
.n-input {
  margin-top: 1vh;
}
</style>
<template>
  <n-spin :show="apiShow">
    <div class="main">
      <n-flex justify="space-around" size="large">
        <div>
          <n-scrollbar style="max-height: 96vh">
            <canvas ref="canvas" width="1371" height="1920" :style="canvasStyle"></canvas>
          </n-scrollbar>
        </div>
        <div>
          <n-card>
            <n-flex justify="space-between">
              <n-switch v-model:value="isDrawingEnabled" :rail-style="railStyle">
                <template #checked>开启绘画</template>
                <template #unchecked>调整绘画</template>
              </n-switch>
              <n-button text @click="saveData"> 保存数据 </n-button>
            </n-flex>
            <br />
            <div v-if="isDrawingEnabled">
              <n-radio
                :checked="checkedTypeValue === 'square'"
                value="square"
                name="graphical"
                @change="handleTypeChange"
              >
                正方形
              </n-radio>
              <n-radio
                :checked="checkedTypeValue === 'rectangle'"
                value="rectangle"
                name="graphical"
                @change="handleTypeChange"
              >
                长方形
              </n-radio>
              <n-radio
                :checked="checkedTypeValue === 'trapezoid'"
                value="trapezoid"
                name="graphical"
                @change="handleTypeChange"
              >
                梯形
              </n-radio>
              <n-radio
                :checked="checkedTypeValue === 'circular'"
                value="circular"
                name="graphical"
                @change="handleTypeChange"
              >
                圆形
              </n-radio>
            </div>
            <n-space vertical>
              <n-slider v-model:value="value" :step="1" @update:value="handleSwitchChange" />
            </n-space>
          </n-card>
          <n-card style="margin-top: 3vh">
            <n-flex justify="space-between">
              <n-a href="/dot"> 点画框 </n-a>
              <n-a href="/line"> 拖动画框 </n-a>
              <n-a href="/surface"> 指定画框 </n-a>
            </n-flex>
          </n-card>
          <n-card style="margin-top: 3vh">
            <n-text depth="3"> 共计 {{ coordinates.length }} 个点读框 </n-text>

            <n-scrollbar style="max-height: 50vh">
              <div class="coordinate">
                <n-input
                  placeholder="音频名称"
                  v-for="(shape, shapeIndex) in coordinates"
                  v-model:value="shape.audio"
                  @mouseenter="handleMouseEnter(shapeIndex)"
                  @mouseleave="handleMouseLeave(shapeIndex)"
                  @update:value="(val: string) => (shape.audio = val)"
                >
                  <template #prefix>
                    <n-icon>
                      <ChatboxOutline />
                    </n-icon>
                  </template>
                  <template #suffix>
                    <n-button text style="font-size: 15px">
                      <n-icon @click="playAudio(shape.audio)">
                        <PlayOutline />
                      </n-icon>
                    </n-button>
                  </template>
                </n-input>
              </div>
            </n-scrollbar>
          </n-card>

          <n-card style="margin-top: 3vh">
            <n-pagination
              mt5vh
              v-model:page="page"
              :page-count="imageList.page.total_page"
              @update:page="onPageChange"
            />
          </n-card>
        </div>
      </n-flex>
    </div>
    <template #description> {{ spinText }} </template>
  </n-spin>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import type { CSSProperties } from 'vue'
import graphicalData from '@/store/tool/graphicalData'
import { ChatboxOutline, PlayOutline } from '@vicons/ionicons5'
import { updateCoordinate } from '@/api/saveCoordinate'

/* 数据 */
import { getPdfImages, type PdfImagesResponse } from '@/api/image'
const apiShow = ref(false)
const spinText = ref('数据加载中')

const coordinates = ref([])
const props = defineProps<{
  id: string
}>()
const pdfId = Number(decodeURIComponent(props.id))
const page = ref(1)
const imageList = ref<PdfImagesResponse>({
  data: [],
  page: { current_page: 1, total_page: 1 }
})
const onPageChange = (newPage: number) => {
  newPage = page.value
}
watch(page, (newPage) => {
  saveData()
  fetchData(newPage)
})
/* -- 数据end -- */

const value = ref(100)
const isDrawingEnabled = ref(false) // true: 绘画模式，false: 调整模式
const hoveredShapeIndex = ref<number | null>(null)

const railStyle = ({ focused, checked }: { focused: boolean; checked: boolean }): CSSProperties => {
  const style: CSSProperties = {}
  if (checked) {
    style.background = '#2080f0'

    if (focused) {
      style.boxShadow = '0 0 0 2px #2080f040'
    }
  } else {
    style.background = '#d03050'
    if (focused) {
      style.boxShadow = '0 0 0 2px #d03050'
    }
  }
  return style
}

const canvasStyle = computed(() => {
  const imageUrl = imageList.value.data.length > 0 ? imageList.value.data[0].url : ''
  return {
    backgroundImage: `url('${imageUrl}')`,
    transform: `scale(${value.value / 100})`,
    transformOrigin: 'top center'
  }
})

// 切换形状
const checkedTypeValue = ref('rectangle')
function handleTypeChange(e: Event) {
  checkedTypeValue.value = (e.target as HTMLInputElement).value
}

// 鼠标绘制相关状态
const canvas = ref<HTMLCanvasElement | null>(null)
let ctx: CanvasRenderingContext2D | null = null
const isDrawing = ref(false)
const startX = ref(0)
const startY = ref(0)
const currentX = ref(0)
const currentY = ref(0)
//缩放预览时 退出绘画模式
function handleSwitchChange() {
  if (isDrawingEnabled.value) {
    isDrawingEnabled.value = false
  }
}
// 存储所有绘制的形状
interface Shape {
  type: string
  audio: string
  startX: number
  startY: number
  endX: number
  endY: number
  isSelected?: boolean // 是否被选中
  aspectRatio?: number // 宽高比（用于保持比例）
  points: { x: number; y: number }[] // 图形的关键点坐标
}

const shapes = ref<Shape[]>([])

// 当前选中的形状
let selectedShape: Shape | null = null
let isDragging = ref(false)
let isResizing = ref(false)
let resizeHandleIndex = -1 // 当前使用的缩放控件索引
let offsetX = 0
let offsetY = 0

const HANDLE_SIZE = 10 // 缩放控件的大小

// 判断音频是否可用

const playAudio = (url: string) => {
  const audio = new Audio(url)
  audio
    .play()
    .then(() => {})
    .catch((error) => {
      alert('音频错误')
    })
}

const fetchData = async (pageNumber: number) => {
  const coordinates = ref([])
  apiShow.value = true
  try {
    const response = await getPdfImages(pdfId, pageNumber)
    imageList.value = response.data
    coordinates.value = response.data.data[0].coordinate
    if (canvas.value) {
      ctx = canvas.value.getContext('2d')

      // 添加鼠标事件监听器
      canvas.value.addEventListener('mousedown', handleMouseDown)
      canvas.value.addEventListener('mousemove', handleMouseMove)
      canvas.value.addEventListener('mouseup', handleMouseUp)
      canvas.value.addEventListener('mouseout', handleMouseUp)

      // 添加右键菜单事件监听器
      canvas.value.addEventListener('contextmenu', handleContextMenu)

      // 初始化 shapes 数组，加载已存储的图形
      if (coordinates.value && coordinates.value.length > 0) {
        shapes.value = coordinates.value.map((shapeData) => {
          const shape: Shape = {
            type: shapeData.type,
            points: shapeData.points,
            isSelected: false,
            audio: shapeData.audio || '',
            startX: 0,
            startY: 0,
            endX: 0,
            endY: 0
          }

          // 根据 points 计算 startX, startY, endX, endY
          switch (shape.type) {
            case 'square':
            case 'rectangle':
              const xValues = shape.points.map((p: any) => p.x)
              const yValues = shape.points.map((p: any) => p.y)
              shape.startX = Math.min(...xValues)
              shape.startY = Math.min(...yValues)
              shape.endX = Math.max(...xValues)
              shape.endY = Math.max(...yValues)
              break
            case 'trapezoid':
              const xVals = shape.points.map((p: any) => p.x)
              const yVals = shape.points.map((p: any) => p.y)
              shape.startX = Math.min(...xVals)
              shape.startY = Math.min(...yVals)
              shape.endX = Math.max(...xVals)
              shape.endY = Math.max(...yVals)
              break
            case 'circular':
              const center = shape.points[0]
              const radius = shape.points[1].x
              shape.startX = center.x - radius
              shape.startY = center.y - radius
              shape.endX = center.x + radius
              shape.endY = center.y + radius
              break
          }

          return shape
        })

        // 绘制所有形状
        drawAllShapes()
      }
    }
  } catch (error) {
    console.error('获取 PDF 列表时出错:', error)
  } finally {
    apiShow.value = false
  }
}
onMounted(() => {
  fetchData(page.value)
})
onBeforeUnmount(() => {
  if (canvas.value) {
    canvas.value.removeEventListener('mousedown', handleMouseDown)
    canvas.value.removeEventListener('mousemove', handleMouseMove)
    canvas.value.removeEventListener('mouseup', handleMouseUp)
    canvas.value.removeEventListener('mouseout', handleMouseUp)

    // 移除右键菜单事件监听器
    canvas.value.removeEventListener('contextmenu', handleContextMenu)
  }
})

// 监控 shapes 的变化，更新 coordinates
watch(
  shapes,
  () => {
    updateCoordinates()
  },
  { deep: true }
)
watch(
  page,
  () => {
    updateCoordinates()
  },
  { deep: true }
)

// 处理鼠标按下事件
function handleMouseDown(e: MouseEvent) {
  const pos = getMousePos(e)
  if (isDrawingEnabled.value) {
    // 绘画模式
    isDrawing.value = true
    startX.value = pos.x
    startY.value = pos.y
  } else {
    // 调整模式
    const shape = getShapeAtPosition(pos)
    if (shape) {
      selectedShape = shape
      shapes.value.forEach((s) => (s.isSelected = false))
      shape.isSelected = true

      // 检查是否点击在缩放控件上
      const handleIndex = getHandleAtPosition(pos, shape)
      if (handleIndex >= 0) {
        isResizing.value = true
        resizeHandleIndex = handleIndex
        if (shape.type !== 'rectangle') {
          // 对于需要保持比例的形状，记录宽高比
          const width = shape.endX - shape.startX
          const height = shape.endY - shape.startY
          shape.aspectRatio = width / height
        }
      } else {
        // 开始拖动形状
        isDragging.value = true
        offsetX = pos.x - shape.startX
        offsetY = pos.y - shape.startY
      }
    } else {
      // 点击空白处，取消选中
      selectedShape = null
      shapes.value.forEach((s) => (s.isSelected = false))
      drawAllShapes()
    }
  }
}

// 处理鼠标移动事件
function handleMouseMove(e: MouseEvent) {
  const pos = getMousePos(e)
  if (isDrawingEnabled.value) {
    // 绘画模式
    if (!isDrawing.value) return
    currentX.value = pos.x
    currentY.value = pos.y

    // 清除画布并重新绘制
    ctx!.clearRect(0, 0, canvas.value!.width, canvas.value!.height)
    drawAllShapes()
    drawCurrentShape()
  } else {
    // 调整模式
    if (isDragging.value && selectedShape) {
      // 更新形状的位置
      const dx = pos.x - offsetX
      const dy = pos.y - offsetY
      const width = selectedShape.endX - selectedShape.startX
      const height = selectedShape.endY - selectedShape.startY
      selectedShape.startX = dx
      selectedShape.startY = dy
      selectedShape.endX = dx + width
      selectedShape.endY = dy + height

      // 重绘所有形状
      ctx!.clearRect(0, 0, canvas.value!.width, canvas.value!.height)
      drawAllShapes()
    } else if (isResizing.value && selectedShape) {
      // 调整形状大小
      resizeShape(selectedShape, pos)

      // 重绘所有形状
      ctx!.clearRect(0, 0, canvas.value!.width, canvas.value!.height)
      drawAllShapes()
    }
  }
}

// 处理鼠标松开或移出事件
function handleMouseUp(e: MouseEvent) {
  if (isDrawingEnabled.value) {
    // 绘画模式
    if (!isDrawing.value) return
    isDrawing.value = false

    // 将当前形状添加到 shapes 数组
    const newShape: Shape = {
      type: checkedTypeValue.value,
      startX: startX.value,
      startY: startY.value,
      endX: currentX.value,
      endY: currentY.value,
      points: [] // 初始化为空数组
    }
    calculateShapePoints(newShape)
    shapes.value.push(newShape)

    // 重新绘制所有形状
    ctx!.clearRect(0, 0, canvas.value!.width, canvas.value!.height)
    drawAllShapes()
  } else {
    // 调整模式
    isDragging.value = false
    isResizing.value = false
    resizeHandleIndex = -1
    if (selectedShape) {
      // 更新选中形状的 points
      calculateShapePoints(selectedShape)
    }
  }
}

// 处理鼠标右键菜单事件
function handleContextMenu(e: MouseEvent) {
  e.preventDefault() // 阻止默认的右键菜单

  const pos = getMousePos(e)
  const shape = getShapeAtPosition(pos)
  if (shape) {
    // 从 shapes 数组中删除该形状
    const index = shapes.value.indexOf(shape)
    if (index > -1) {
      shapes.value.splice(index, 1)
      ctx!.clearRect(0, 0, canvas.value!.width, canvas.value!.height)
      drawAllShapes()
    }
  }
}

// 获取鼠标在画布上的位置，考虑缩放比例
function getMousePos(e: MouseEvent) {
  const rect = canvas.value!.getBoundingClientRect()
  const scaleX = canvas.value!.width / rect.width
  const scaleY = canvas.value!.height / rect.height
  return {
    x: (e.clientX - rect.left) * scaleX,
    y: (e.clientY - rect.top) * scaleY
  }
}

// 绘制所有已保存的形状
function drawAllShapes() {
  if (!ctx) return

  ctx.clearRect(0, 0, canvas.value!.width, canvas.value!.height)

  shapes.value.forEach((shape, index) => {
    ctx!.beginPath()
    const { startX, startY, endX, endY } = shape
    switch (shape.type) {
      case 'square':
        drawSquare(startX, startY, endX, endY)
        break
      case 'rectangle':
        drawRectangle(startX, startY, endX, endY)
        break
      case 'trapezoid':
        drawTrapezoid(startX, startY, endX, endY)
        break
      case 'circular':
        drawCircle(startX, startY, endX, endY)
        break
      default:
        drawShape(shape)
    }

    if (index === hoveredShapeIndex.value) {
      ctx!.strokeStyle = 'rgba(0, 255, 0, 0.5)'
      ctx!.fillStyle = 'rgba(0, 255, 0, 0.5)'
    } else {
      ctx!.strokeStyle = shape.isSelected ? 'blue' : 'red'
      ctx!.fillStyle = 'transparent'
    }

    ctx!.lineWidth = 2
    ctx!.stroke()
    ctx!.fill()

    if (shape.isSelected) {
      drawSelection(shape)
    }
  })
}
// 绘制单个形状
function drawShape(shape: Shape) {
  if (ctx) {
    ctx.beginPath()
    const points = shape.points
    ctx.moveTo(points[0].x, points[0].y)
    for (let i = 1; i < points.length; i++) {
      ctx.lineTo(points[i].x, points[i].y)
    }
    ctx.closePath()

    // 设置样式
    ctx.strokeStyle = 'red'
    ctx.lineWidth = 2
    ctx.fillStyle = 'transparent'

    // 绘制形状
    ctx.fill()
    ctx.stroke()
  }
}
function handleMouseEnter(shapeIndex: number) {
  //鼠标移入时相应图形背景色变为半透明绿色
  hoveredShapeIndex.value = shapeIndex
  drawAllShapes()
}
function handleMouseLeave(shapeIndex: number) {
  //鼠标移出时变为透明色
  hoveredShapeIndex.value = null
  drawAllShapes()
}
// 绘制当前正在绘制的形状
function drawCurrentShape() {
  if (!ctx) return
  ctx!.beginPath()
  switch (checkedTypeValue.value) {
    case 'square':
      drawSquare(startX.value, startY.value, currentX.value, currentY.value)
      break
    case 'rectangle':
      drawRectangle(startX.value, startY.value, currentX.value, currentY.value)
      break
    case 'trapezoid':
      drawTrapezoid(startX.value, startY.value, currentX.value, currentY.value)
      break
    case 'circular':
      drawCircle(startX.value, startY.value, currentX.value, currentY.value)
      break
  }
  ctx!.strokeStyle = 'red'
  ctx!.lineWidth = 2
  ctx!.stroke()
}

// 绘制正方形
function drawSquare(x1: number, y1: number, x2: number, y2: number) {
  const dx = x2 - x1
  const dy = y2 - y1
  const side = Math.min(Math.abs(dx), Math.abs(dy))
  const width = side * Math.sign(dx)
  const height = side * Math.sign(dy)
  ctx!.rect(x1, y1, width, height)
}

// 绘制长方形
function drawRectangle(x1: number, y1: number, x2: number, y2: number) {
  const width = x2 - x1
  const height = y2 - y1
  ctx!.rect(x1, y1, width, height)
}

// 绘制梯形
function drawTrapezoid(x1: number, y1: number, x2: number, y2: number) {
  const baseWidth = x2 - x1
  const topWidth = baseWidth * 0.6 // 顶边宽度为底边的60%
  const offset = (baseWidth - topWidth) / 2

  ctx!.moveTo(x1 + offset, y1)
  ctx!.lineTo(x1 + offset + topWidth, y1)
  ctx!.lineTo(x2, y2)
  ctx!.lineTo(x1, y2)
  ctx!.closePath()
}

// 绘制圆形
function drawCircle(x1: number, y1: number, x2: number, y2: number) {
  const centerX = (x1 + x2) / 2
  const centerY = (y1 + y2) / 2
  const radius = Math.hypot(x2 - x1, y2 - y1) / 2
  ctx!.arc(centerX, centerY, radius, 0, 2 * Math.PI)
}

// 绘制选中形状的边框和缩放控件
function drawSelection(shape: Shape) {
  const { startX, startY, endX, endY } = shape
  ctx!.save()
  ctx!.strokeStyle = 'blue'
  ctx!.lineWidth = 1
  ctx!.setLineDash([5, 5])
  ctx!.strokeRect(startX, startY, endX - startX, endY - startY)
  ctx!.restore()

  // 绘制缩放控件
  const handles = getResizeHandles(shape)
  handles.forEach((handle, index) => {
    ctx!.fillStyle = 'white'
    ctx!.strokeStyle = 'blue'
    ctx!.lineWidth = 1
    ctx!.fillRect(handle.x - HANDLE_SIZE / 2, handle.y - HANDLE_SIZE / 2, HANDLE_SIZE, HANDLE_SIZE)
    ctx!.strokeRect(
      handle.x - HANDLE_SIZE / 2,
      handle.y - HANDLE_SIZE / 2,
      HANDLE_SIZE,
      HANDLE_SIZE
    )
  })
}

// 获取缩放控件的位置
function getResizeHandles(shape: Shape) {
  const { startX, startY, endX, endY } = shape
  const midX = (startX + endX) / 2
  const midY = (startY + endY) / 2
  const handles = [
    { x: startX, y: startY }, // 左上角（0）
    { x: midX, y: startY }, // 上边中点（1）
    { x: endX, y: startY }, // 右上角（2）
    { x: endX, y: midY }, // 右边中点（3）
    { x: endX, y: endY }, // 右下角（4）
    { x: midX, y: endY }, // 下边中点（5）
    { x: startX, y: endY }, // 左下角（6）
    { x: startX, y: midY } // 左边中点（7）
  ]
  if (shape.type !== 'rectangle') {
    // 如果需要保持比例，只保留四个角的控件
    return [handles[0], handles[2], handles[4], handles[6]]
  }
  return handles
}

// 根据鼠标位置获取被点击的缩放控件
function getHandleAtPosition(pos: { x: number; y: number }, shape: Shape) {
  const handles = getResizeHandles(shape)
  for (let i = 0; i < handles.length; i++) {
    const handle = handles[i]
    if (
      pos.x >= handle.x - HANDLE_SIZE / 2 &&
      pos.x <= handle.x + HANDLE_SIZE / 2 &&
      pos.y >= handle.y - HANDLE_SIZE / 2 &&
      pos.y <= handle.y + HANDLE_SIZE / 2
    ) {
      return i
    }
  }
  return -1
}

// 调整形状大小
function resizeShape(shape: Shape, pos: { x: number; y: number }) {
  const { startX, startY, endX, endY } = shape
  let newStartX = startX
  let newStartY = startY
  let newEndX = endX
  let newEndY = endY

  switch (resizeHandleIndex) {
    case 0: // 左上角
      newStartX = pos.x
      newStartY = pos.y
      break
    case 2: // 右上角
      newEndX = pos.x
      newStartY = pos.y
      break
    case 4: // 右下角
      newEndX = pos.x
      newEndY = pos.y
      break
    case 6: // 左下角
      newStartX = pos.x
      newEndY = pos.y
      break
    case 1: // 上边中点
      newStartY = pos.y
      break
    case 3: // 右边中点
      newEndX = pos.x
      break
    case 5: // 下边中点
      newEndY = pos.y
      break
    case 7: // 左边中点
      newStartX = pos.x
      break
  }

  if (shape.type !== 'rectangle') {
    // 对于其他形状，需要保持宽高比
    const width = newEndX - newStartX
    const height = width / shape.aspectRatio!
    if (resizeHandleIndex === 0 || resizeHandleIndex === 2) {
      newStartY = newEndY - height
    } else if (resizeHandleIndex === 4 || resizeHandleIndex === 6) {
      newEndY = newStartY + height
    }
  }

  // 更新形状的起始和结束坐标
  shape.startX = newStartX
  shape.startY = newStartY
  shape.endX = newEndX
  shape.endY = newEndY

  // 更新形状的 points
  calculateShapePoints(shape)
}

// 根据鼠标位置获取被点击的形状
function getShapeAtPosition(pos: { x: number; y: number }): Shape | null {
  // 从后往前遍历，这样可以选择最上层的形状
  for (let i = shapes.value.length - 1; i >= 0; i--) {
    const shape = shapes.value[i]
    if (isPointInShape(pos, shape)) {
      return shape
    }
  }
  return null
}

// 判断点是否在形状内
function isPointInShape(pos: { x: number; y: number }, shape: Shape): boolean {
  ctx!.beginPath()
  switch (shape.type) {
    case 'square':
      drawSquare(shape.startX, shape.startY, shape.endX, shape.endY)
      break
    case 'rectangle':
      drawRectangle(shape.startX, shape.startY, shape.endX, shape.endY)
      break
    case 'trapezoid':
      drawTrapezoid(shape.startX, shape.startY, shape.endX, shape.endY)
      break
    case 'circular':
      drawCircle(shape.startX, shape.startY, shape.endX, shape.endY)
      break
  }
  return ctx!.isPointInPath(pos.x, pos.y)
}

// 计算并更新形状的关键点坐标
function calculateShapePoints(shape: Shape) {
  const { startX, startY, endX, endY } = shape
  let points: { x: number; y: number }[] = []

  switch (shape.type) {
    case 'square':
    case 'rectangle':
      points = [
        { x: startX, y: startY }, // 左上
        { x: endX, y: startY }, // 右上
        { x: endX, y: endY }, // 右下
        { x: startX, y: endY } // 左下
      ]
      break
    case 'trapezoid':
      const baseWidth = endX - startX
      const topWidth = baseWidth * 0.6
      const offset = (baseWidth - topWidth) / 2
      points = [
        { x: startX + offset, y: startY }, // 顶边左点
        { x: startX + offset + topWidth, y: startY }, // 顶边右点
        { x: endX, y: endY }, // 底边右点
        { x: startX, y: endY } // 底边左点
      ]
      break
    case 'circular':
      const centerX = (startX + endX) / 2
      const centerY = (startY + endY) / 2
      const radius = Math.hypot(endX - startX, endY - startY) / 2
      points = [
        { x: centerX, y: centerY }, // 圆心
        { x: radius, y: 0 } // 半径，可视为向量
      ]
      break
  }

  shape.points = points
}

// 更新 coordinates 数组，并调用外部函数
function updateCoordinates() {
  coordinates.value = shapes.value.map((shape, shapeIndex) => ({
    shapeIndex,
    type: shape.type,
    audio: shape.audio || '',
    points: shape.points.map((point) => ({ x: point.x, y: point.y }))
  }))
}

async function saveData() {
  apiShow.value = true
  spinText.value = '数据提交中~'
  try {
    const response = await updateCoordinate(imageList.value.data[0]['id'], {
      coordinate: coordinates.value
    })
    // 处理返回结果
    if ('success' in response) {
      console.log('更新成功:', response.message)
    } else {
      console.error('更新失败:', response.error)
    }
  } catch (error) {
    console.error('更新失败')
  } finally {
    spinText.value = '数据加载中'
    apiShow.value = false
  }
}
</script>
